package com.lan3g.Test.Model;

import com.lan3g.Test.pojo.User;
import com.lan3g.Test.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class RegisterModel {

        public boolean register(User user) {
            Connection conn = JDBCUtil.getConn();
            try {
                // 开启事务
                //   conn.setAutoCommit(false);
                String sqlInsert =
                        "INSERT INTO user (username,pwd,nickname" +
                                ") VALUES (?,?,?)";
                PreparedStatement psInsert
                        = conn.prepareStatement(sqlInsert);
                psInsert.setString(1, user.getUsername());
                psInsert.setString(2, user.getPassword());
                psInsert.setString(3, user.getNickName());

                psInsert.executeUpdate();
                psInsert.close();// 直接关闭

                // 查询刚刚插入的主键
                String getIDSQL = "SELECT MAX(uid) FROM user";
                PreparedStatement psID = conn.prepareStatement(getIDSQL);
                ResultSet rs = psID.executeQuery();
                rs.next();
                int uid = rs.getInt(1);
                rs.close();
                psID.close();


                return true;// 注册成功
            } catch (Exception e) {

                    e.printStackTrace();
              }
            return false;
        }

        public boolean hasThisName(String username) {
            String sql = "SELECT count(*) FROM user" +
                    " WHERE username = ?";
            Connection conn = JDBCUtil.getConn();
            try {
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ResultSet resultSet = ps.executeQuery();
                resultSet.next();
                int count = resultSet.getInt(1);

                resultSet.close();
                ps.close();

                return count > 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }

